import { Component } from 'react'
import React from 'react'
import ReactDOM from 'react-dom'


class App extends Component {
  state = {
    msg: '',
    msg2: '',
    list: [
      { id: 1, msg: '段九德', msg2: '臭豆腐' },
      { id: 2, msg: '花无缺', msg2: '二狗子' },
      { id: 3, msg: '徐缺', msg2: '炸天帮徐缺' }
    ]
  }
  render() {
    return <div>
      <input type="text" placeholder='请输入评论人' name='msg' onChange={this.handleChange} value={this.state.msg} />
      <textarea onChange={this.handleChange} value={this.state.msg2} name="msg2" id="" cols="30" rows="10" placeholder='请输入评论内容'></textarea>
      <button onClick={this.btn}>发表评论</button>
      <button onClick={this.btn2}>清空评论</button>
      {/* {this.state.list.length === 0 ? (<div>暂无评论</div>) :
        (<ul>
          {this.state.list.map((item, index) => (
            <li key={item.id}>
              <p>评论人:{item.name}</p>
              <p>评论内容:{item.n}</p>
              <button>删除</button>
            </li>
          ))}
        </ul>)} */}
      {this.renderList()}

    </div>
  }
  renderList() {
    if (this.state.list.length === 0) {
      return <div>暂无评论</div>
    }
    return <ul>
      {this.state.list.map((item, index) => (
        <li key={item.id}>
          <p>评论人:{item.msg}</p>
          <p>评论内容:{item.msg2}</p>
          <button onClick={() => this.delete(item.id)}>删除</button>
        </li>
      ))}
    </ul>
  }
  handleChange = (e) => {
    let { name, value } = e.target
    this.setState({
      [name]: value
    })
  }
  btn = () => {
    const { msg, msg2, list } = this.state
    if (!msg || !msg2) {
      return alert('不能为空！')
    } else {
      this.setState({
        list: [{ id: Date.now(), msg, msg2 }, ...list],
        msg: '',
        msg2: ''
      })
    }
  }
  btn2 = () => {
    this.setState({
      list: []
    })
  }
  delete = (id) => {
    // console.log(id);
    this.setState({
      list: this.state.list.filter(v => v.id !== id)
    })
  }
}

ReactDOM.render(<App></App>, document.getElementById('root'))